

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>nlp_architect.models.tagging &mdash; NLP Architect by Intel® AI Lab 0.5.2 documentation</title>
  

  
  
  
  

  
  <script type="text/javascript" src="../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../../../_static/jquery.js"></script>
        <script type="text/javascript" src="../../../_static/underscore.js"></script>
        <script type="text/javascript" src="../../../_static/doctools.js"></script>
        <script type="text/javascript" src="../../../_static/language_data.js"></script>
        <script type="text/javascript" src="../../../_static/install.js"></script>
        <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../../_static/nlp_arch_theme.css" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Mono" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:100,900" type="text/css" />
    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../index.html">
          

          
            
            <img src="../../../_static/logo.png" class="logo" alt="Logo"/>
          
          </a>

          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul>
<li class="toctree-l1"><a class="reference internal" href="../../../quick_start.html">Quick start</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../installation.html">Installation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../publications.html">Publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../tutorials.html">Jupyter Tutorials</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../model_zoo.html">Model Zoo</a></li>
</ul>
<p class="caption"><span class="caption-text">NLP/NLU Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../tagging/sequence_tagging.html">Sequence Tagging</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../sentiment.html">Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../bist_parser.html">Dependency Parsing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../intent.html">Intent Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../lm.html">Language Models</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../information_extraction.html">Information Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../transformers.html">Transformers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../archived/additional.html">Additional Models</a></li>
</ul>
<p class="caption"><span class="caption-text">Optimized Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../quantized_bert.html">Quantized BERT</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../transformers_distillation.html">Transformers Distillation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../sparse_gnmt.html">Sparse Neural Machine Translation</a></li>
</ul>
<p class="caption"><span class="caption-text">Solutions</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../absa_solution.html">Aspect Based Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../term_set_expansion.html">Set Expansion</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../trend_analysis.html">Trend Analysis</a></li>
</ul>
<p class="caption"><span class="caption-text">For Developers</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../generated_api/nlp_architect_api_index.html">nlp_architect API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../developer_guide.html">Developer Guide</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../index.html">NLP Architect by Intel® AI Lab</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../index.html">Module code</a> &raquo;</li>
        
          <li><a href="../models.html">nlp_architect.models</a> &raquo;</li>
        
      <li>nlp_architect.models.tagging</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for nlp_architect.models.tagging</h1><div class="highlight"><pre>
<span></span><span class="c1"># ******************************************************************************</span>
<span class="c1"># Copyright 2017-2019 Intel Corporation</span>
<span class="c1">#</span>
<span class="c1"># Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span>
<span class="c1"># you may not use this file except in compliance with the License.</span>
<span class="c1"># You may obtain a copy of the License at</span>
<span class="c1">#</span>
<span class="c1">#     http://www.apache.org/licenses/LICENSE-2.0</span>
<span class="c1">#</span>
<span class="c1"># Unless required by applicable law or agreed to in writing, software</span>
<span class="c1"># distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span>
<span class="c1"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span>
<span class="c1"># See the License for the specific language governing permissions and</span>
<span class="c1"># limitations under the License.</span>
<span class="c1"># ******************************************************************************</span>
<span class="kn">import</span> <span class="nn">io</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">pickle</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span>

<span class="kn">import</span> <span class="nn">torch</span>
<span class="kn">import</span> <span class="nn">torch.optim</span> <span class="k">as</span> <span class="nn">optim</span>
<span class="kn">from</span> <span class="nn">torch.nn</span> <span class="kn">import</span> <span class="n">CrossEntropyLoss</span>
<span class="kn">from</span> <span class="nn">torch.nn</span> <span class="kn">import</span> <span class="n">functional</span> <span class="k">as</span> <span class="n">F</span>
<span class="kn">from</span> <span class="nn">torch.utils.data</span> <span class="kn">import</span> <span class="n">DataLoader</span><span class="p">,</span> <span class="n">SequentialSampler</span><span class="p">,</span> <span class="n">TensorDataset</span>
<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tqdm</span><span class="p">,</span> <span class="n">trange</span>

<span class="kn">from</span> <span class="nn">nlp_architect.data.sequential_tagging</span> <span class="kn">import</span> <span class="n">TokenClsInputExample</span>
<span class="kn">from</span> <span class="nn">nlp_architect.models</span> <span class="kn">import</span> <span class="n">TrainableModel</span>
<span class="kn">from</span> <span class="nn">nlp_architect.nn.torch.layers</span> <span class="kn">import</span> <span class="n">CRF</span>
<span class="kn">from</span> <span class="nn">nlp_architect.nn.torch.distillation</span> <span class="kn">import</span> <span class="n">TeacherStudentDistill</span>
<span class="kn">from</span> <span class="nn">nlp_architect.utils.metrics</span> <span class="kn">import</span> <span class="n">tagging</span>
<span class="kn">from</span> <span class="nn">nlp_architect.utils.text</span> <span class="kn">import</span> <span class="n">Vocabulary</span><span class="p">,</span> <span class="n">char_to_id</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>


<div class="viewcode-block" id="NeuralTagger"><a class="viewcode-back" href="../../../tagging/sequence_tagging.html#nlp_architect.models.tagging.NeuralTagger">[docs]</a><span class="k">class</span> <span class="nc">NeuralTagger</span><span class="p">(</span><span class="n">TrainableModel</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Simple neural tagging model</span>
<span class="sd">    Supports pytorch embedder models, multi-gpu training, KD from teacher models</span>

<span class="sd">    Args:</span>
<span class="sd">        embedder_model: pytorch embedder model (valid nn.Module model)</span>
<span class="sd">        word_vocab (Vocabulary): word vocabulary</span>
<span class="sd">        labels (List, optional): list of labels. Defaults to None</span>
<span class="sd">        use_crf (bool, optional): use CRF a the classifier (instead of Softmax). Defaults to False.</span>
<span class="sd">        device (str, optional): device backend. Defatuls to &#39;cpu&#39;.</span>
<span class="sd">        n_gpus (int, optional): number of gpus. Default to 0.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">embedder_model</span><span class="p">,</span>
        <span class="n">word_vocab</span><span class="p">:</span> <span class="n">Vocabulary</span><span class="p">,</span>
        <span class="n">labels</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">use_crf</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
        <span class="n">device</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s2">&quot;cpu&quot;</span><span class="p">,</span>
        <span class="n">n_gpus</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">NeuralTagger</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">embedder_model</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">labels</span> <span class="o">=</span> <span class="n">labels</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">labels</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>  <span class="c1"># +1 for padding</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">label_str_id</span> <span class="o">=</span> <span class="p">{</span><span class="n">l</span><span class="p">:</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">l</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">labels</span><span class="p">,</span> <span class="mi">1</span><span class="p">)}</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">label_id_str</span> <span class="o">=</span> <span class="p">{</span><span class="n">v</span><span class="p">:</span> <span class="n">k</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">label_str_id</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">word_vocab</span> <span class="o">=</span> <span class="n">word_vocab</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span> <span class="o">=</span> <span class="n">use_crf</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">crf</span> <span class="o">=</span> <span class="n">CRF</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span><span class="p">,</span> <span class="n">batch_first</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">=</span> <span class="n">n_gpus</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span><span class="p">)</span>

<div class="viewcode-block" id="NeuralTagger.convert_to_tensors"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.convert_to_tensors">[docs]</a>    <span class="k">def</span> <span class="nf">convert_to_tensors</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">examples</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">TokenClsInputExample</span><span class="p">],</span>
        <span class="n">max_seq_length</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">128</span><span class="p">,</span>
        <span class="n">max_word_length</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">12</span><span class="p">,</span>
        <span class="n">pad_id</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
        <span class="n">labels_pad_id</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
        <span class="n">include_labels</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">True</span><span class="p">,</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="n">TensorDataset</span><span class="p">:</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Convert examples to valid tagger dataset</span>

<span class="sd">        Args:</span>
<span class="sd">            examples (List[TokenClsInputExample]): List of examples</span>
<span class="sd">            max_seq_length (int, optional): max words per sentence. Defaults to 128.</span>
<span class="sd">            max_word_length (int, optional): max characters in a word. Defaults to 12.</span>
<span class="sd">            pad_id (int, optional): padding int id. Defaults to 0.</span>
<span class="sd">            labels_pad_id (int, optional): labels padding id. Defaults to 0.</span>
<span class="sd">            include_labels (bool, optional): include labels in dataset. Defaults to True.</span>

<span class="sd">        Returns:</span>
<span class="sd">            TensorDataset: TensorDataset for given examples</span>
<span class="sd">        &quot;&quot;&quot;</span>

        <span class="n">features</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">example</span> <span class="ow">in</span> <span class="n">examples</span><span class="p">:</span>
            <span class="n">word_tokens</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">word_vocab</span><span class="p">[</span><span class="n">t</span><span class="p">]</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">example</span><span class="o">.</span><span class="n">tokens</span><span class="p">]</span>
            <span class="n">labels</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
                <span class="n">labels</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">label_str_id</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">l</span><span class="p">)</span> <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="n">example</span><span class="o">.</span><span class="n">label</span><span class="p">]</span>
            <span class="n">word_chars</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">example</span><span class="o">.</span><span class="n">tokens</span><span class="p">:</span>
                <span class="n">word_chars</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="n">char_to_id</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">word</span><span class="p">])</span>

            <span class="c1"># cut up to max length</span>
            <span class="n">word_tokens</span> <span class="o">=</span> <span class="n">word_tokens</span><span class="p">[:</span><span class="n">max_seq_length</span><span class="p">]</span>
            <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
                <span class="n">labels</span> <span class="o">=</span> <span class="n">labels</span><span class="p">[:</span><span class="n">max_seq_length</span><span class="p">]</span>
            <span class="n">word_chars</span> <span class="o">=</span> <span class="n">word_chars</span><span class="p">[:</span><span class="n">max_seq_length</span><span class="p">]</span>
            <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">word_chars</span><span class="p">)):</span>
                <span class="n">word_chars</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">word_chars</span><span class="p">[</span><span class="n">i</span><span class="p">][:</span><span class="n">max_word_length</span><span class="p">]</span>
            <span class="n">mask</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="nb">len</span><span class="p">(</span><span class="n">word_tokens</span><span class="p">)</span>

            <span class="c1"># Zero-pad up to the sequence length.</span>
            <span class="n">padding_length</span> <span class="o">=</span> <span class="n">max_seq_length</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">word_tokens</span><span class="p">)</span>
            <span class="n">input_ids</span> <span class="o">=</span> <span class="n">word_tokens</span> <span class="o">+</span> <span class="p">([</span><span class="n">pad_id</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span><span class="p">)</span>
            <span class="n">mask</span> <span class="o">=</span> <span class="n">mask</span> <span class="o">+</span> <span class="p">([</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
                <span class="n">label_ids</span> <span class="o">=</span> <span class="n">labels</span> <span class="o">+</span> <span class="p">([</span><span class="n">labels_pad_id</span><span class="p">]</span> <span class="o">*</span> <span class="n">padding_length</span><span class="p">)</span>

            <span class="n">word_char_ids</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="c1"># pad word vectors</span>
            <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">word_chars</span><span class="p">)):</span>
                <span class="n">word_char_ids</span><span class="o">.</span><span class="n">append</span><span class="p">(</span>
                    <span class="n">word_chars</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="p">([</span><span class="n">pad_id</span><span class="p">]</span> <span class="o">*</span> <span class="p">(</span><span class="n">max_word_length</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">word_chars</span><span class="p">[</span><span class="n">i</span><span class="p">])))</span>
                <span class="p">)</span>

            <span class="c1"># pad word vectors with remaining zero vectors</span>
            <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">padding_length</span><span class="p">):</span>
                <span class="n">word_char_ids</span><span class="o">.</span><span class="n">append</span><span class="p">(([</span><span class="n">pad_id</span><span class="p">]</span> <span class="o">*</span> <span class="n">max_word_length</span><span class="p">))</span>

            <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">input_ids</span><span class="p">)</span> <span class="o">==</span> <span class="n">max_seq_length</span>
            <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
                <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">label_ids</span><span class="p">)</span> <span class="o">==</span> <span class="n">max_seq_length</span>
            <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">word_char_ids</span><span class="p">)</span> <span class="o">==</span> <span class="n">max_seq_length</span>
            <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">word_char_ids</span><span class="p">)):</span>
                <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">word_char_ids</span><span class="p">[</span><span class="n">i</span><span class="p">])</span> <span class="o">==</span> <span class="n">max_word_length</span>

            <span class="n">features</span><span class="o">.</span><span class="n">append</span><span class="p">(</span>
                <span class="n">InputFeatures</span><span class="p">(</span>
                    <span class="n">input_ids</span><span class="p">,</span>
                    <span class="n">word_char_ids</span><span class="p">,</span>
                    <span class="n">mask</span><span class="o">=</span><span class="n">mask</span><span class="p">,</span>
                    <span class="n">label_id</span><span class="o">=</span><span class="n">label_ids</span> <span class="k">if</span> <span class="n">include_labels</span> <span class="k">else</span> <span class="kc">None</span><span class="p">,</span>
                <span class="p">)</span>
            <span class="p">)</span>

        <span class="c1"># Convert to Tensors and build dataset</span>
        <span class="n">all_input_ids</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">input_ids</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>
        <span class="n">all_char_ids</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">char_ids</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>
        <span class="n">masks</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">mask</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>

        <span class="k">if</span> <span class="n">include_labels</span><span class="p">:</span>
            <span class="n">all_label_ids</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="n">f</span><span class="o">.</span><span class="n">label_id</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">features</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">long</span><span class="p">)</span>
            <span class="n">dataset</span> <span class="o">=</span> <span class="n">TensorDataset</span><span class="p">(</span><span class="n">all_input_ids</span><span class="p">,</span> <span class="n">all_char_ids</span><span class="p">,</span> <span class="n">masks</span><span class="p">,</span> <span class="n">all_label_ids</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">dataset</span> <span class="o">=</span> <span class="n">TensorDataset</span><span class="p">(</span><span class="n">all_input_ids</span><span class="p">,</span> <span class="n">all_char_ids</span><span class="p">,</span> <span class="n">masks</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">dataset</span></div>

<div class="viewcode-block" id="NeuralTagger.get_optimizer"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.get_optimizer">[docs]</a>    <span class="k">def</span> <span class="nf">get_optimizer</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">opt_fn</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">lr</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mf">0.001</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Get default optimizer</span>

<span class="sd">        Args:</span>
<span class="sd">            lr (int, optional): learning rate. Defaults to 0.001.</span>

<span class="sd">        Returns:</span>
<span class="sd">            torch.optim.Optimizer: optimizer</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">params</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">parameters</span><span class="p">()</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
            <span class="n">params</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">params</span><span class="p">)</span> <span class="o">+</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="o">.</span><span class="n">parameters</span><span class="p">())</span>
        <span class="k">if</span> <span class="n">opt_fn</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">opt_fn</span> <span class="o">=</span> <span class="n">optim</span><span class="o">.</span><span class="n">Adam</span>
        <span class="k">return</span> <span class="n">opt_fn</span><span class="p">(</span><span class="n">params</span><span class="p">,</span> <span class="n">lr</span><span class="o">=</span><span class="n">lr</span><span class="p">)</span></div>

<div class="viewcode-block" id="NeuralTagger.batch_mapper"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.batch_mapper">[docs]</a>    <span class="nd">@staticmethod</span>
    <span class="k">def</span> <span class="nf">batch_mapper</span><span class="p">(</span><span class="n">batch</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Map batch to correct input names</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">mapping</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;words&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="s2">&quot;word_chars&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="s2">&quot;mask&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">2</span><span class="p">]}</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span> <span class="o">==</span> <span class="mi">4</span><span class="p">:</span>
            <span class="n">mapping</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s2">&quot;labels&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">3</span><span class="p">]})</span>
        <span class="k">return</span> <span class="n">mapping</span></div>

<div class="viewcode-block" id="NeuralTagger.train"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.train">[docs]</a>    <span class="k">def</span> <span class="nf">train</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">train_data_set</span><span class="p">:</span> <span class="n">DataLoader</span><span class="p">,</span>
        <span class="n">dev_data_set</span><span class="p">:</span> <span class="n">DataLoader</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">test_data_set</span><span class="p">:</span> <span class="n">DataLoader</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">epochs</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span>
        <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span>
        <span class="n">optimizer</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">max_grad_norm</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">5.0</span><span class="p">,</span>
        <span class="n">logging_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span>
        <span class="n">save_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">100</span><span class="p">,</span>
        <span class="n">save_path</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">distiller</span><span class="p">:</span> <span class="n">TeacherStudentDistill</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Train a tagging model</span>

<span class="sd">        Args:</span>
<span class="sd">            train_data_set (DataLoader): train examples dataloader. If distiller object is</span>
<span class="sd">            provided train examples should contain a tuple of student/teacher data examples.</span>
<span class="sd">            dev_data_set (DataLoader, optional): dev examples dataloader. Defaults to None.</span>
<span class="sd">            test_data_set (DataLoader, optional): test examples dataloader. Defaults to None.</span>
<span class="sd">            epochs (int, optional): num of epochs to train. Defaults to 3.</span>
<span class="sd">            batch_size (int, optional): batch size. Defaults to 8.</span>
<span class="sd">            optimizer (fn, optional): optimizer function. Defaults to default model optimizer.</span>
<span class="sd">            max_grad_norm (float, optional): max gradient norm. Defaults to 5.0.</span>
<span class="sd">            logging_steps (int, optional): number of steps between logging. Defaults to 50.</span>
<span class="sd">            save_steps (int, optional): number of steps between model saves. Defaults to 100.</span>
<span class="sd">            save_path (str, optional): model output path. Defaults to None.</span>
<span class="sd">            distiller (TeacherStudentDistill, optional): KD model for training the model using</span>
<span class="sd">            a teacher model. Defaults to None.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="n">optimizer</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">optimizer</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_optimizer</span><span class="p">()</span>
        <span class="n">train_batch_size</span> <span class="o">=</span> <span class="n">batch_size</span> <span class="o">*</span> <span class="nb">max</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;***** Running training *****&quot;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Num examples = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">train_data_set</span><span class="o">.</span><span class="n">dataset</span><span class="p">))</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Num Epochs = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">epochs</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Instantaneous batch size per GPU/CPU = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Total batch size = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">train_batch_size</span><span class="p">)</span>
        <span class="n">global_step</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span>
        <span class="n">epoch_it</span> <span class="o">=</span> <span class="n">trange</span><span class="p">(</span><span class="n">epochs</span><span class="p">,</span> <span class="n">desc</span><span class="o">=</span><span class="s2">&quot;Epoch&quot;</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="n">epoch_it</span><span class="p">:</span>
            <span class="n">step_it</span> <span class="o">=</span> <span class="n">tqdm</span><span class="p">(</span><span class="n">train_data_set</span><span class="p">,</span> <span class="n">desc</span><span class="o">=</span><span class="s2">&quot;Train iteration&quot;</span><span class="p">)</span>
            <span class="n">avg_loss</span> <span class="o">=</span> <span class="mi">0</span>
            <span class="k">for</span> <span class="n">step</span><span class="p">,</span> <span class="n">batch</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">step_it</span><span class="p">):</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">train</span><span class="p">()</span>
                <span class="k">if</span> <span class="n">distiller</span><span class="p">:</span>
                    <span class="n">batch</span><span class="p">,</span> <span class="n">t_batch</span> <span class="o">=</span> <span class="n">batch</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>
                    <span class="n">t_batch</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">t_batch</span><span class="p">)</span>
                    <span class="n">t_logits</span> <span class="o">=</span> <span class="n">distiller</span><span class="o">.</span><span class="n">get_teacher_logits</span><span class="p">(</span><span class="n">t_batch</span><span class="p">)</span>
                <span class="n">batch</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">batch</span><span class="p">)</span>
                <span class="n">inputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_mapper</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
                <span class="n">logits</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs</span><span class="p">)</span>
                <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
                    <span class="n">loss</span> <span class="o">=</span> <span class="o">-</span><span class="mf">1.0</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">],</span> <span class="n">mask</span><span class="o">=</span><span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;mask&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="mf">0.0</span><span class="p">)</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">loss_fn</span> <span class="o">=</span> <span class="n">CrossEntropyLoss</span><span class="p">(</span><span class="n">ignore_index</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
                    <span class="n">loss</span> <span class="o">=</span> <span class="n">loss_fn</span><span class="p">(</span><span class="n">logits</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span><span class="p">),</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
                <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                    <span class="n">loss</span> <span class="o">=</span> <span class="n">loss</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>

                <span class="c1"># add distillation loss if activated</span>
                <span class="k">if</span> <span class="n">distiller</span><span class="p">:</span>
                    <span class="n">loss</span> <span class="o">=</span> <span class="n">distiller</span><span class="o">.</span><span class="n">distill_loss</span><span class="p">(</span><span class="n">loss</span><span class="p">,</span> <span class="n">logits</span><span class="p">,</span> <span class="n">t_logits</span><span class="p">)</span>

                <span class="n">loss</span><span class="o">.</span><span class="n">backward</span><span class="p">()</span>
                <span class="n">torch</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">clip_grad_norm_</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">parameters</span><span class="p">(),</span> <span class="n">max_grad_norm</span><span class="p">)</span>

                <span class="n">optimizer</span><span class="o">.</span><span class="n">step</span><span class="p">()</span>
                <span class="c1"># self.model.zero_grad()</span>
                <span class="n">optimizer</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span>
                <span class="n">global_step</span> <span class="o">+=</span> <span class="mi">1</span>
                <span class="n">avg_loss</span> <span class="o">+=</span> <span class="n">loss</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
                <span class="k">if</span> <span class="n">global_step</span> <span class="o">%</span> <span class="n">logging_steps</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                    <span class="k">if</span> <span class="n">step</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
                        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span>
                            <span class="s2">&quot; global_step = </span><span class="si">%s</span><span class="s2">, average loss = </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">global_step</span><span class="p">,</span> <span class="n">avg_loss</span> <span class="o">/</span> <span class="n">step</span>
                        <span class="p">)</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">_get_eval</span><span class="p">(</span><span class="n">dev_data_set</span><span class="p">,</span> <span class="s2">&quot;dev&quot;</span><span class="p">)</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">_get_eval</span><span class="p">(</span><span class="n">test_data_set</span><span class="p">,</span> <span class="s2">&quot;test&quot;</span><span class="p">)</span>
                <span class="k">if</span> <span class="n">save_path</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">global_step</span> <span class="o">%</span> <span class="n">save_steps</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">save_model</span><span class="p">(</span><span class="n">save_path</span><span class="p">)</span></div>

<div class="viewcode-block" id="NeuralTagger.train_pseudo"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.train_pseudo">[docs]</a>    <span class="k">def</span> <span class="nf">train_pseudo</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">labeled_data_set</span><span class="p">:</span> <span class="n">DataLoader</span><span class="p">,</span>
        <span class="n">unlabeled_data_set</span><span class="p">:</span> <span class="n">DataLoader</span><span class="p">,</span>
        <span class="n">distiller</span><span class="p">:</span> <span class="n">TeacherStudentDistill</span><span class="p">,</span>
        <span class="n">dev_data_set</span><span class="p">:</span> <span class="n">DataLoader</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">test_data_set</span><span class="p">:</span> <span class="n">DataLoader</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">batch_size_l</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span>
        <span class="n">batch_size_ul</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span>
        <span class="n">epochs</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">100</span><span class="p">,</span>
        <span class="n">optimizer</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">max_grad_norm</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">5.0</span><span class="p">,</span>
        <span class="n">logging_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span>
        <span class="n">save_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">100</span><span class="p">,</span>
        <span class="n">save_path</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">save_best</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Train a tagging model</span>

<span class="sd">        Args:</span>
<span class="sd">            train_data_set (DataLoader): train examples dataloader. If distiller object is</span>
<span class="sd">            provided train examples should contain a tuple of student/teacher data examples.</span>
<span class="sd">            dev_data_set (DataLoader, optional): dev examples dataloader. Defaults to None.</span>
<span class="sd">            test_data_set (DataLoader, optional): test examples dataloader. Defaults to None.</span>
<span class="sd">            batch_size_l (int, optional): batch size for the labeled dataset. Defaults to 8.</span>
<span class="sd">            batch_size_ul (int, optional): batch size for the unlabeled dataset. Defaults to 8.</span>
<span class="sd">            epochs (int, optional): num of epochs to train. Defaults to 100.</span>
<span class="sd">            optimizer (fn, optional): optimizer function. Defaults to default model optimizer.</span>
<span class="sd">            max_grad_norm (float, optional): max gradient norm. Defaults to 5.0.</span>
<span class="sd">            logging_steps (int, optional): number of steps between logging. Defaults to 50.</span>
<span class="sd">            save_steps (int, optional): number of steps between model saves. Defaults to 100.</span>
<span class="sd">            save_path (str, optional): model output path. Defaults to None.</span>
<span class="sd">            save_best (str, optional): wether to save model when result is best on dev set</span>
<span class="sd">            distiller (TeacherStudentDistill, optional): KD model for training the model using</span>
<span class="sd">            a teacher model. Defaults to None.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="n">optimizer</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">optimizer</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_optimizer</span><span class="p">()</span>
        <span class="n">train_batch_size_l</span> <span class="o">=</span> <span class="n">batch_size_l</span> <span class="o">*</span> <span class="nb">max</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span><span class="p">)</span>
        <span class="n">train_batch_size_ul</span> <span class="o">=</span> <span class="n">batch_size_ul</span> <span class="o">*</span> <span class="nb">max</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;***** Running training *****&quot;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Num labeled examples = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">labeled_data_set</span><span class="o">.</span><span class="n">dataset</span><span class="p">))</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Num unlabeled examples = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">unlabeled_data_set</span><span class="o">.</span><span class="n">dataset</span><span class="p">))</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Instantaneous labeled batch size per GPU/CPU = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">batch_size_l</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Instantaneous unlabeled batch size per GPU/CPU = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">batch_size_ul</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Total batch size labeled= </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">train_batch_size_l</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Total batch size unlabeled= </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">train_batch_size_ul</span><span class="p">)</span>
        <span class="n">global_step</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span>
        <span class="n">avg_loss</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">iter_l</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">labeled_data_set</span><span class="p">)</span>
        <span class="n">iter_ul</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">unlabeled_data_set</span><span class="p">)</span>
        <span class="n">epoch_l</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">epoch_ul</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">s_idx</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>
        <span class="n">best_dev</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">best_test</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
            <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;labeled epoch=</span><span class="si">%d</span><span class="s2">, unlabeled epoch=</span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">epoch_l</span><span class="p">,</span> <span class="n">epoch_ul</span><span class="p">)</span>
            <span class="n">loss_labeled</span> <span class="o">=</span> <span class="mi">0</span>
            <span class="n">loss_unlabeled</span> <span class="o">=</span> <span class="mi">0</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">batch_l</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">iter_l</span><span class="p">)</span>
                <span class="n">s_idx</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
                <span class="n">iter_l</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">labeled_data_set</span><span class="p">)</span>
                <span class="n">epoch_l</span> <span class="o">+=</span> <span class="mi">1</span>
                <span class="n">batch_l</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">iter_l</span><span class="p">)</span>
                <span class="n">s_idx</span> <span class="o">=</span> <span class="mi">0</span>
                <span class="n">avg_loss</span> <span class="o">=</span> <span class="mi">0</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">batch_ul</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">iter_ul</span><span class="p">)</span>
            <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
                <span class="n">iter_ul</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">unlabeled_data_set</span><span class="p">)</span>
                <span class="n">epoch_ul</span> <span class="o">+=</span> <span class="mi">1</span>
                <span class="n">batch_ul</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">iter_ul</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">epoch_ul</span> <span class="o">&gt;</span> <span class="n">epochs</span><span class="p">:</span>
                <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;Done&quot;</span><span class="p">)</span>
                <span class="k">return</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">train</span><span class="p">()</span>
            <span class="n">batch_l</span><span class="p">,</span> <span class="n">t_batch_l</span> <span class="o">=</span> <span class="n">batch_l</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>
            <span class="n">batch_ul</span><span class="p">,</span> <span class="n">t_batch_ul</span> <span class="o">=</span> <span class="n">batch_ul</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>
            <span class="n">t_batch_l</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">t_batch_l</span><span class="p">)</span>
            <span class="n">t_batch_ul</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">t_batch_ul</span><span class="p">)</span>
            <span class="n">t_logits</span> <span class="o">=</span> <span class="n">distiller</span><span class="o">.</span><span class="n">get_teacher_logits</span><span class="p">(</span><span class="n">t_batch_l</span><span class="p">)</span>
            <span class="n">t_logits_ul</span> <span class="o">=</span> <span class="n">distiller</span><span class="o">.</span><span class="n">get_teacher_logits</span><span class="p">(</span><span class="n">t_batch_ul</span><span class="p">)</span>
            <span class="n">batch_l</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">batch_l</span><span class="p">)</span>
            <span class="n">batch_ul</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">batch_ul</span><span class="p">)</span>
            <span class="n">inputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_mapper</span><span class="p">(</span><span class="n">batch_l</span><span class="p">)</span>
            <span class="n">inputs_ul</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_mapper</span><span class="p">(</span><span class="n">batch_ul</span><span class="p">)</span>
            <span class="n">logits</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs</span><span class="p">)</span>
            <span class="n">logits_ul</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs_ul</span><span class="p">)</span>
            <span class="n">t_labels</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">F</span><span class="o">.</span><span class="n">log_softmax</span><span class="p">(</span><span class="n">t_logits_ul</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">2</span><span class="p">),</span> <span class="n">dim</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
                <span class="n">loss_labeled</span> <span class="o">=</span> <span class="o">-</span><span class="mf">1.0</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">],</span> <span class="n">mask</span><span class="o">=</span><span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;mask&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="mf">0.0</span><span class="p">)</span>
                <span class="n">loss_unlabeled</span> <span class="o">=</span> <span class="o">-</span><span class="mf">1.0</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="p">(</span><span class="n">logits_ul</span><span class="p">,</span> <span class="n">t_labels</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">inputs_ul</span><span class="p">[</span><span class="s2">&quot;mask&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="mf">0.0</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">loss_fn</span> <span class="o">=</span> <span class="n">CrossEntropyLoss</span><span class="p">(</span><span class="n">ignore_index</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
                <span class="n">loss_labeled</span> <span class="o">=</span> <span class="n">loss_fn</span><span class="p">(</span><span class="n">logits</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span><span class="p">),</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
                <span class="n">loss_unlabeled</span> <span class="o">=</span> <span class="n">loss_fn</span><span class="p">(</span><span class="n">logits_ul</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span><span class="p">),</span> <span class="n">t_labels</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>

            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                <span class="n">loss_labeled</span> <span class="o">=</span> <span class="n">loss_labeled</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
                <span class="n">loss_unlabeled</span> <span class="o">=</span> <span class="n">loss_unlabeled</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>

            <span class="c1"># add distillation loss</span>
            <span class="n">loss_labeled</span> <span class="o">=</span> <span class="n">distiller</span><span class="o">.</span><span class="n">distill_loss</span><span class="p">(</span><span class="n">loss_labeled</span><span class="p">,</span> <span class="n">logits</span><span class="p">,</span> <span class="n">t_logits</span><span class="p">)</span>
            <span class="n">loss_unlabeled</span> <span class="o">=</span> <span class="n">distiller</span><span class="o">.</span><span class="n">distill_loss</span><span class="p">(</span><span class="n">loss_unlabeled</span><span class="p">,</span> <span class="n">logits_ul</span><span class="p">,</span> <span class="n">t_logits_ul</span><span class="p">)</span>

            <span class="c1"># sum labeled and unlabeled losses</span>
            <span class="n">loss</span> <span class="o">=</span> <span class="n">loss_labeled</span> <span class="o">+</span> <span class="n">loss_unlabeled</span>
            <span class="n">loss</span><span class="o">.</span><span class="n">backward</span><span class="p">()</span>
            <span class="n">torch</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">clip_grad_norm_</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">parameters</span><span class="p">(),</span> <span class="n">max_grad_norm</span><span class="p">)</span>
            <span class="n">optimizer</span><span class="o">.</span><span class="n">step</span><span class="p">()</span>
            <span class="c1"># self.model.zero_grad()</span>
            <span class="n">optimizer</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span>
            <span class="n">global_step</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="n">avg_loss</span> <span class="o">+=</span> <span class="n">loss</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
            <span class="k">if</span> <span class="n">global_step</span> <span class="o">%</span> <span class="n">logging_steps</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">s_idx</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
                    <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span>
                        <span class="s2">&quot; global_step = </span><span class="si">%s</span><span class="s2">, average loss = </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">global_step</span><span class="p">,</span> <span class="n">avg_loss</span> <span class="o">/</span> <span class="n">s_idx</span>
                    <span class="p">)</span>
                <span class="n">dev</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_get_eval</span><span class="p">(</span><span class="n">dev_data_set</span><span class="p">,</span> <span class="s2">&quot;dev&quot;</span><span class="p">)</span>
                <span class="n">test</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_get_eval</span><span class="p">(</span><span class="n">test_data_set</span><span class="p">,</span> <span class="s2">&quot;test&quot;</span><span class="p">)</span>
                <span class="k">if</span> <span class="n">dev</span> <span class="o">&gt;</span> <span class="n">best_dev</span><span class="p">:</span>
                    <span class="n">best_dev</span> <span class="o">=</span> <span class="n">dev</span>
                    <span class="n">best_test</span> <span class="o">=</span> <span class="n">test</span>
                    <span class="k">if</span> <span class="n">save_path</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">save_best</span><span class="p">:</span>
                        <span class="bp">self</span><span class="o">.</span><span class="n">save_model</span><span class="p">(</span><span class="n">save_path</span><span class="p">)</span>
                <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;Best result: dev= </span><span class="si">%s</span><span class="s2">, test= </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">best_dev</span><span class="p">),</span> <span class="nb">str</span><span class="p">(</span><span class="n">best_test</span><span class="p">))</span>
            <span class="k">if</span> <span class="n">save_path</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">global_step</span> <span class="o">%</span> <span class="n">save_steps</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">save_model</span><span class="p">(</span><span class="n">save_path</span><span class="p">)</span></div>

    <span class="k">def</span> <span class="nf">_get_eval</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ds</span><span class="p">,</span> <span class="n">set_name</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">ds</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">logits</span><span class="p">,</span> <span class="n">out_label_ids</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">evaluate</span><span class="p">(</span><span class="n">ds</span><span class="p">)</span>
            <span class="n">res</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">evaluate_predictions</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">out_label_ids</span><span class="p">)</span>
            <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot; </span><span class="si">{}</span><span class="s2"> set F1 = </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">set_name</span><span class="p">,</span> <span class="n">res</span><span class="p">[</span><span class="s2">&quot;f1&quot;</span><span class="p">]))</span>
            <span class="k">return</span> <span class="n">res</span><span class="p">[</span><span class="s2">&quot;f1&quot;</span><span class="p">]</span>
        <span class="k">return</span> <span class="kc">None</span>

<div class="viewcode-block" id="NeuralTagger.to"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.to">[docs]</a>    <span class="k">def</span> <span class="nf">to</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">device</span><span class="o">=</span><span class="s2">&quot;cpu&quot;</span><span class="p">,</span> <span class="n">n_gpus</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Put model on given device</span>

<span class="sd">        Args:</span>
<span class="sd">            device (str, optional): device backend. Defaults to &#39;cpu&#39;.</span>
<span class="sd">            n_gpus (int, optional): number of gpus. Defaults to 0.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">)</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">n_gpus</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">DataParallel</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">)</span>
                <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">crf</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">DataParallel</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">=</span> <span class="n">n_gpus</span></div>

<div class="viewcode-block" id="NeuralTagger.evaluate"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.evaluate">[docs]</a>    <span class="k">def</span> <span class="nf">evaluate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data_set</span><span class="p">:</span> <span class="n">DataLoader</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Run evaluation on given dataloader</span>

<span class="sd">        Args:</span>
<span class="sd">            data_set (DataLoader): a data loader to run evaluation on</span>

<span class="sd">        Returns:</span>
<span class="sd">            logits, labels (if labels are given)</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;***** Running inference *****&quot;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot; Batch size: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">data_set</span><span class="o">.</span><span class="n">batch_size</span><span class="p">))</span>
        <span class="n">eval_loss</span> <span class="o">=</span> <span class="mf">0.0</span>
        <span class="n">preds</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="n">out_label_ids</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">for</span> <span class="n">batch</span> <span class="ow">in</span> <span class="n">tqdm</span><span class="p">(</span><span class="n">data_set</span><span class="p">,</span> <span class="n">desc</span><span class="o">=</span><span class="s2">&quot;Inference iteration&quot;</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">eval</span><span class="p">()</span>
            <span class="n">batch</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">batch</span><span class="p">)</span>
            <span class="k">with</span> <span class="n">torch</span><span class="o">.</span><span class="n">no_grad</span><span class="p">():</span>
                <span class="n">inputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_mapper</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
                <span class="n">logits</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs</span><span class="p">)</span>
                <span class="k">if</span> <span class="s2">&quot;labels&quot;</span> <span class="ow">in</span> <span class="n">inputs</span><span class="p">:</span>
                    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
                        <span class="n">loss</span> <span class="o">=</span> <span class="o">-</span><span class="mf">1.0</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">],</span> <span class="n">mask</span><span class="o">=</span><span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;mask&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="mf">0.0</span><span class="p">)</span>
                    <span class="k">else</span><span class="p">:</span>
                        <span class="n">loss_fn</span> <span class="o">=</span> <span class="n">CrossEntropyLoss</span><span class="p">(</span><span class="n">ignore_index</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
                        <span class="n">loss</span> <span class="o">=</span> <span class="n">loss_fn</span><span class="p">(</span><span class="n">logits</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span><span class="p">),</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
                    <span class="n">eval_loss</span> <span class="o">+=</span> <span class="n">loss</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
            <span class="n">model_output</span> <span class="o">=</span> <span class="n">logits</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span>
            <span class="n">model_out_label_ids</span> <span class="o">=</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span> <span class="k">if</span> <span class="s2">&quot;labels&quot;</span> <span class="ow">in</span> <span class="n">inputs</span> <span class="k">else</span> <span class="kc">None</span>
            <span class="k">if</span> <span class="n">preds</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
                <span class="n">preds</span> <span class="o">=</span> <span class="n">model_output</span>
                <span class="n">out_label_ids</span> <span class="o">=</span> <span class="n">model_out_label_ids</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">preds</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">cat</span><span class="p">((</span><span class="n">preds</span><span class="p">,</span> <span class="n">model_output</span><span class="p">),</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
                <span class="n">out_label_ids</span> <span class="o">=</span> <span class="p">(</span>
                    <span class="n">torch</span><span class="o">.</span><span class="n">cat</span><span class="p">((</span><span class="n">out_label_ids</span><span class="p">,</span> <span class="n">model_out_label_ids</span><span class="p">),</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
                    <span class="k">if</span> <span class="n">out_label_ids</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
                    <span class="k">else</span> <span class="kc">None</span>
                <span class="p">)</span>
        <span class="n">output</span> <span class="o">=</span> <span class="p">(</span><span class="n">preds</span><span class="p">,)</span>
        <span class="k">if</span> <span class="n">out_label_ids</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">output</span> <span class="o">=</span> <span class="n">output</span> <span class="o">+</span> <span class="p">(</span><span class="n">out_label_ids</span><span class="p">,)</span>
        <span class="k">return</span> <span class="n">output</span></div>

<div class="viewcode-block" id="NeuralTagger.evaluate_predictions"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.evaluate_predictions">[docs]</a>    <span class="k">def</span> <span class="nf">evaluate_predictions</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Evaluate given logits on truth labels</span>

<span class="sd">        Args:</span>
<span class="sd">            logits: logits of model</span>
<span class="sd">            label_ids: truth label ids</span>

<span class="sd">        Returns:</span>
<span class="sd">            dict: dictionary containing P/R/F1 metrics</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">active_positions</span> <span class="o">=</span> <span class="n">label_ids</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mf">0.0</span>
        <span class="n">active_labels</span> <span class="o">=</span> <span class="n">label_ids</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)[</span><span class="n">active_positions</span><span class="p">]</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
            <span class="n">logits_shape</span> <span class="o">=</span> <span class="n">logits</span><span class="o">.</span><span class="n">size</span><span class="p">()</span>
            <span class="n">decode_ap</span> <span class="o">=</span> <span class="n">active_positions</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="n">logits_shape</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">logits_shape</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="o">!=</span> <span class="mf">0.0</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                <span class="n">decode_fn</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="o">.</span><span class="n">module</span><span class="o">.</span><span class="n">decode</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">decode_fn</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="o">.</span><span class="n">decode</span>
            <span class="n">logits</span> <span class="o">=</span> <span class="n">decode_fn</span><span class="p">(</span><span class="n">logits</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">),</span> <span class="n">mask</span><span class="o">=</span><span class="n">decode_ap</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">))</span>
            <span class="n">logits</span> <span class="o">=</span> <span class="p">[</span><span class="n">l</span> <span class="k">for</span> <span class="n">ll</span> <span class="ow">in</span> <span class="n">logits</span> <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="n">ll</span><span class="p">]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">active_logits</span> <span class="o">=</span> <span class="n">logits</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">label_id_str</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)[</span><span class="n">active_positions</span><span class="p">]</span>
            <span class="n">logits</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">F</span><span class="o">.</span><span class="n">log_softmax</span><span class="p">(</span><span class="n">active_logits</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">),</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
            <span class="n">logits</span> <span class="o">=</span> <span class="n">logits</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span>
        <span class="n">out_label_ids</span> <span class="o">=</span> <span class="n">active_labels</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span>
        <span class="n">y_true</span><span class="p">,</span> <span class="n">y_pred</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">extract_labels</span><span class="p">(</span><span class="n">out_label_ids</span><span class="p">,</span> <span class="n">logits</span><span class="p">)</span>
        <span class="n">p</span><span class="p">,</span> <span class="n">r</span><span class="p">,</span> <span class="n">f1</span> <span class="o">=</span> <span class="n">tagging</span><span class="p">(</span><span class="n">y_pred</span><span class="p">,</span> <span class="n">y_true</span><span class="p">)</span>
        <span class="k">return</span> <span class="p">{</span><span class="s2">&quot;p&quot;</span><span class="p">:</span> <span class="n">p</span><span class="p">,</span> <span class="s2">&quot;r&quot;</span><span class="p">:</span> <span class="n">r</span><span class="p">,</span> <span class="s2">&quot;f1&quot;</span><span class="p">:</span> <span class="n">f1</span><span class="p">}</span></div>

<div class="viewcode-block" id="NeuralTagger.extract_labels"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.extract_labels">[docs]</a>    <span class="k">def</span> <span class="nf">extract_labels</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">,</span> <span class="n">logits</span><span class="p">):</span>
        <span class="n">label_map</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">label_id_str</span>
        <span class="n">y_true</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">y_pred</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">p</span><span class="p">,</span> <span class="n">y</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">):</span>
            <span class="n">y_pred</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">label_map</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s2">&quot;O&quot;</span><span class="p">))</span>
            <span class="n">y_true</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">label_map</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="s2">&quot;O&quot;</span><span class="p">))</span>
        <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">y_true</span><span class="p">)</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">y_pred</span><span class="p">)</span>
        <span class="k">return</span> <span class="p">(</span><span class="n">y_true</span><span class="p">,</span> <span class="n">y_pred</span><span class="p">)</span></div>

<div class="viewcode-block" id="NeuralTagger.inference"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.inference">[docs]</a>    <span class="k">def</span> <span class="nf">inference</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">examples</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">TokenClsInputExample</span><span class="p">],</span> <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">64</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Do inference on given examples</span>

<span class="sd">        Args:</span>
<span class="sd">            examples (List[TokenClsInputExample]): examples</span>
<span class="sd">            batch_size (int, optional): batch size. Defaults to 64.</span>

<span class="sd">        Returns:</span>
<span class="sd">            List(tuple): a list of tuples of tokens, tags predicted by model</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">data_set</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">convert_to_tensors</span><span class="p">(</span><span class="n">examples</span><span class="p">,</span> <span class="n">include_labels</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
        <span class="n">inf_sampler</span> <span class="o">=</span> <span class="n">SequentialSampler</span><span class="p">(</span><span class="n">data_set</span><span class="p">)</span>
        <span class="n">inf_dataloader</span> <span class="o">=</span> <span class="n">DataLoader</span><span class="p">(</span><span class="n">data_set</span><span class="p">,</span> <span class="n">sampler</span><span class="o">=</span><span class="n">inf_sampler</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span><span class="p">)</span>
        <span class="n">logits</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">evaluate</span><span class="p">(</span><span class="n">inf_dataloader</span><span class="p">)</span>
        <span class="n">active_positions</span> <span class="o">=</span> <span class="n">data_set</span><span class="o">.</span><span class="n">tensors</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data_set</span><span class="p">),</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="o">!=</span> <span class="mf">0.0</span>
        <span class="n">logits</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">F</span><span class="o">.</span><span class="n">log_softmax</span><span class="p">(</span><span class="n">logits</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">dim</span><span class="o">=</span><span class="mi">2</span><span class="p">),</span> <span class="n">dim</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
        <span class="n">res_ids</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">logits</span><span class="o">.</span><span class="n">size</span><span class="p">()[</span><span class="mi">0</span><span class="p">]):</span>
            <span class="n">res_ids</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">logits</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">active_positions</span><span class="p">[</span><span class="n">i</span><span class="p">]]</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span><span class="o">.</span><span class="n">numpy</span><span class="p">())</span>
        <span class="n">output</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">tag_ids</span><span class="p">,</span> <span class="n">ex</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">res_ids</span><span class="p">,</span> <span class="n">examples</span><span class="p">):</span>
            <span class="n">tokens</span> <span class="o">=</span> <span class="n">ex</span><span class="o">.</span><span class="n">tokens</span>
            <span class="n">tags</span> <span class="o">=</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">label_id_str</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="s2">&quot;O&quot;</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">tag_ids</span><span class="p">]</span>
            <span class="n">output</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">tokens</span><span class="p">,</span> <span class="n">tags</span><span class="p">))</span>
        <span class="k">return</span> <span class="n">output</span></div>

<div class="viewcode-block" id="NeuralTagger.save_model"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.save_model">[docs]</a>    <span class="k">def</span> <span class="nf">save_model</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">output_dir</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Save model to path</span>

<span class="sd">        Args:</span>
<span class="sd">            output_dir (str): output directory</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">torch</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">output_dir</span><span class="p">,</span> <span class="s2">&quot;model.bin&quot;</span><span class="p">))</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">use_crf</span><span class="p">:</span>
            <span class="n">torch</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">crf</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">output_dir</span><span class="p">,</span> <span class="s2">&quot;crf.bin&quot;</span><span class="p">))</span>
        <span class="k">with</span> <span class="n">io</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">output_dir</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;labels.txt&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fw</span><span class="p">:</span>
            <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">labels</span><span class="p">:</span>
                <span class="n">fw</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{}</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">l</span><span class="p">))</span>
        <span class="k">with</span> <span class="n">io</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">output_dir</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;w_vocab.dat&quot;</span><span class="p">,</span> <span class="s2">&quot;wb&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fw</span><span class="p">:</span>
            <span class="n">pickle</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">word_vocab</span><span class="p">,</span> <span class="n">fw</span><span class="p">)</span></div>

<div class="viewcode-block" id="NeuralTagger.load_model"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.load_model">[docs]</a>    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">load_model</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">model_path</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Load a tagger model from given path</span>

<span class="sd">        Args:</span>
<span class="sd">            model_path (str): model path</span>

<span class="sd">            NeuralTagger: tagger model loaded from path</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="c1"># Load a trained model and vocabulary from given path</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">model_path</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">FileNotFoundError</span>
        <span class="k">with</span> <span class="n">io</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">model_path</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;labels.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
            <span class="n">labels</span> <span class="o">=</span> <span class="p">[</span><span class="n">l</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="n">fp</span><span class="o">.</span><span class="n">readlines</span><span class="p">()]</span>

        <span class="k">with</span> <span class="n">io</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">model_path</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;w_vocab.dat&quot;</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
            <span class="n">w_vocab</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">fp</span><span class="p">)</span>
        <span class="c1"># load model.bin into</span>
        <span class="n">model_file_path</span> <span class="o">=</span> <span class="n">model_path</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;model.bin&quot;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">model_file_path</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">FileNotFoundError</span>
        <span class="n">model</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">model_file_path</span><span class="p">)</span>
        <span class="n">new_class</span> <span class="o">=</span> <span class="bp">cls</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">w_vocab</span><span class="p">,</span> <span class="n">labels</span><span class="p">)</span>
        <span class="n">crf_file_path</span> <span class="o">=</span> <span class="n">model_path</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;crf.bin&quot;</span>
        <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">crf_file_path</span><span class="p">):</span>
            <span class="n">new_class</span><span class="o">.</span><span class="n">use_crf</span> <span class="o">=</span> <span class="kc">True</span>
            <span class="n">new_class</span><span class="o">.</span><span class="n">crf</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">crf_file_path</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">new_class</span><span class="o">.</span><span class="n">use_crf</span> <span class="o">=</span> <span class="kc">False</span>
        <span class="k">return</span> <span class="n">new_class</span></div>

<div class="viewcode-block" id="NeuralTagger.get_logits"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.NeuralTagger.get_logits">[docs]</a>    <span class="k">def</span> <span class="nf">get_logits</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">batch</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">eval</span><span class="p">()</span>
        <span class="n">inputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_mapper</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
        <span class="n">outputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">outputs</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span></div></div>


<div class="viewcode-block" id="InputFeatures"><a class="viewcode-back" href="../../../generated_api/nlp_architect.models.html#nlp_architect.models.tagging.InputFeatures">[docs]</a><span class="k">class</span> <span class="nc">InputFeatures</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;A single set of features of data.&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">input_ids</span><span class="p">,</span> <span class="n">char_ids</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">label_id</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">input_ids</span> <span class="o">=</span> <span class="n">input_ids</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">char_ids</span> <span class="o">=</span> <span class="n">char_ids</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">mask</span> <span class="o">=</span> <span class="n">mask</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">label_id</span> <span class="o">=</span> <span class="n">label_id</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>